import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
let scene, camera, renderer, controls

/* 
  uniform变量
*/
function init() {
  scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.set(0, 0, 5)
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  controls = new OrbitControls(camera, renderer.domElement)
  controls.enableDamping = true

  const axesHelper = new THREE.AxesHelper(5)
  scene.add(axesHelper)
};

function createBasic () {
  // 1. 创建平面
  const geometry = new THREE.PlaneGeometry(1, 1)
  // 自己自定义属性position2，然后赋值为geometry.attributes.position
  geometry.setAttribute('position2', geometry.attributes.position)
  
  // 2. 创建材质
  const material = new THREE.ShaderMaterial({
    // attribute只能用于顶点着色器，传入几何图形待处理的属性 position uv
    // attribute vec3 position2注意在main函数外面去写，表示要去查找几何体的position2属性，
    // 下面就可以使用position2
    vertexShader: `
      attribute vec3 position2;
      void main () {
        gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position2, 1.0);
      }
    `,
    // 片元着色器
    fragmentShader: `
      void main () {
        gl_FragColor = vec4(0, 1.0, 0, 0.9);
      }
    `
  })
  // 3. 创建物体
  const mesh = new THREE.Mesh(geometry, material)
  scene.add(mesh)
}

function renderLoop() {
  renderer.render(scene, camera)
  controls.update()
  requestAnimationFrame(renderLoop)
}

init()
createBasic()
renderLoop() 

